import { Injectable } from '@angular/core';
import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpInterceptor, HttpErrorResponse, HttpResponse
} from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import {finalize, tap} from "rxjs/operators";
import {Response} from "./Response";
import {Router} from "@angular/router";

@Injectable()
export class HeroInterceptor implements HttpInterceptor {

  constructor(private router:Router) {}

  intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<Response>> {
    const req = request.clone();
    return next.handle(req).pipe(
      tap(event=>{
        if(event instanceof HttpResponse) {
        }
      },error=>{
        if (error.status == 401){
          localStorage.removeItem("user");
          this.router.navigateByUrl('/login');
        }
        console.log(error)
      }),
      finalize(()=>{

      })
    );
  }

  private handleError(error: HttpErrorResponse){
    if (typeof error.error?.code === 'number') {
      console.error(`服务器端发生错误，状态码：${error.error.code}`);
    } else {
      console.error('请求失败');
    }
    const err = new Error(error.message);
    throwError(() => err);
  }

}
